﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Test.control;

namespace Test
{
    public partial class Form1 : Form
    {
        private System.Threading.Timer timer1, timer2;
        private List<TestClient> testClients = new List<TestClient>();
        private List<TestClient> addClients = new List<TestClient>();
        private int index = 1;
        private object addObj = new object();
        private DateTime oldTime;

        public static string ip= "192.168.2.4";
        public static int gatePort = 8101;
        public static int sendPort = 5721;

        public Form1()
        {
            InitializeComponent();
            this.init();
        }

        private void init()
        {
            oldTime = DateTime.Now;
            Time.time = 0;
            timer1 = new System.Threading.Timer(this.Update, null, 50, 50);
            timer2 = new System.Threading.Timer(this.SendUpdate, null, 100, 100);
        }

        #region 链接
        public void Update(object state)
        {
            Time.time = (int)(DateTime.Now - oldTime).TotalMilliseconds*0.001f;
            int stateError = 0;
            int stateOk = 0;
            for (int i = 0; i < testClients.Count; i++)
            {
                testClients[i].Update();
                if (testClients[i].state < 0)
                {
                    stateError++;
                }
                else if (testClients[i].state == 4)
                {
                    stateOk++;
                }
            }

            this.BeginInvoke((Action)(() =>
            {
                this.label1.Text = "异常:" + stateError + ",ok:" + stateOk + ",总计:" + testClients.Count;
            }));
            

            if (addClients.Count > 0)
            {
                lock (addObj)
                {
                    testClients.AddRange(addClients);

                    addClients.Clear();
                }
            }
        }


        private void button1_Click(object sender, EventArgs e)
        {
            int v;
            if (int.TryParse(this.txtNum.Text, out v))
            {
                for (int i = 1; i <= v; i++)
                {
                    ClientItemUI ui = new ClientItemUI();
                    this.list.Controls.Add(ui);
                    TestClient testClient = new TestClient(this,"ttc4c6b27b5bf9ea8710", "test" + index.ToString(), index, ui);
                    testClient.pwd = Code.datas[i - 1];
                    index++;
                    _ = testClient.getServerList();
                    addClients.Add(testClient);
                }
            }
        }
        #endregion

        #region 发送
        private void btnSend_Click(object sender, EventArgs e)
        {
            //RestartSend();
        }
        public void SendUpdate(object state)
        {
            int start, end;
            long t = DateTime.Now.Ticks;
            if (int.TryParse(txt1.Text, out start) && int.TryParse(txt2.Text, out end))
            {
                if (start > 0 && end > 0)
                {

                    string url =string.Format("http://{0}:{1}/tt",ip,sendPort);

                    for (int i = start; i <= end; i++)
                    {
                        Dictionary<string, string> headers = new Dictionary<string, string>();
                        headers.Add("x-nonce-str", "");
                        headers.Add("x-timestamp", "");
                        headers.Add("x-signature", "");
                        headers.Add("x-roomid", "test" + i.ToString());
                        headers.Add("x-msg-type", "live_comment");

                        var bd ="[{\"msg_id\":\"" + (t + i).ToString() + "\",\"sec_openid\":\"xxxx\",\"sec_gift_id\":\"xxxx\",\"gift_num\":123,\"gift_value\":10000,\"avatar_url\":\"xxx\",\"nickname\":\"xxxx\",\"timestamp\":1649068964}]";
                        HttpPost(url, bd, headers: headers);
                    }
                }
            }
        }
        public void SendGzUpdate(object state)
        {
            int start, end;
            if (int.TryParse(txt1.Text, out start) && int.TryParse(txt2.Text, out end))
            {
                if (start > 0 && end > 0)
                {
                    for (int k = start; k <= end; k++)
                    {
                        string  url =string.Format("http://{0}:{1}/gz?appid=ttc4c6b27b5bf9ea8710&roomid=test{2}&uid=1001&uname=xxxx&img=xxx", ip, sendPort, k);
                        Console.WriteLine(url);
                        HttpPost(url);
                    }
                }
            }
        }

        public static string HttpPost(string url, string postData = null, string contentType = "application/json", int timeOut = 120, Dictionary<string, string> headers = null)
        {
            postData = postData ?? "";
            ServicePointManager.DefaultConnectionLimit = 512;
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.ContentType = contentType;
            request.Timeout = timeOut * 1000;
            if (headers != null)
            {
                foreach (var header in headers)
                    request.Headers.Add(header.Key, header.Value);
            }
            request.Method = "POST";
            byte[] data = Encoding.UTF8.GetBytes(postData);
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (var httpStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    return httpStreamReader.ReadToEnd();
                }
            }
            catch(Exception ex)
            {
                return "";
            }
        }
        #endregion
    }
}
